<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      ref="toolbar"
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :default-config="toolbarConfig"
    />
    <Editor
      v-model="valueHtml"
      style="height: 500px; overflow-y: hidden"
      :default-config="editorConfig"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import type { IToolbarConfig } from "@wangeditor/editor";
import { onBeforeUnmount, ref, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const editorRef = shallowRef();
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:modelValue"]);
// 内容 HTML
const valueHtml = ref(props.modelValue);

const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    "bold",
    "fontSize",
    "italic",
    "underline",
    "indent",
    "lineHeight",
    "undo",
    "redo",
    "bgColor",
    "fontFamily",
    "justifyLeft",
    "justifyRight",
    "numberedList",
    "bulletedList",
  ],
};
const editorConfig = { placeholder: "请输入内容..." };
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleChange = () => {
  emit("update:modelValue", valueHtml.value);
};
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  console.log(editorRef.value.getConfig());
};
</script>

<style></style>
